﻿using IM.Easy.Entity.Scheduled;
using IM.Easy.ScheduledServices.IRefitApi;
using Quartz;
using Refit;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;

namespace IM.Easy.ScheduledServices.Jobs
{
    [DisallowConcurrentExecution]
    public class RemoteJob : IJob
    {
        private readonly ISqlSugarClient _db;
        private readonly HttpClient _httpClient;

        public RemoteJob(ISqlSugarClient db, HttpClient httpClient)
        {
            _db = db;
            _httpClient = httpClient;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            var jobData = context.MergedJobDataMap;
            var baseUrl = jobData.GetString("remote_url") ?? "http://example.com/api";
            var method = (jobData.GetString("remote_method") ?? "GET").ToUpper();
            var queryParams = new Dictionary<string, string>();

            foreach (var key in jobData.Keys)
            {
                if (key.StartsWith("param_"))
                {
                    var value = jobData.GetString(key);
                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        queryParams.Add(key.Substring(6), value);
                    }
                }
            }

            var fullUrl = $"{baseUrl}?{string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={kvp.Value}"))}";

            HttpResponseMessage response = null;

            try
            {
                response = method switch
                {
                    "GET" => await _httpClient.GetAsync(fullUrl),
                    "POST" => await _httpClient.PostAsync(fullUrl, null),
                    "PUT" => await _httpClient.PutAsync(fullUrl, null),
                    "DELETE" => await _httpClient.DeleteAsync(fullUrl),
                    _ => throw new NotSupportedException($"HTTP method '{method}' is not supported."),
                };
                response.EnsureSuccessStatusCode();
                var result = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"这是请求结果{result}");
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"远程请求失败：{ex.Message}");
                // 可在此记录日志或进行异常处理
            }
            finally
            {
                response?.Dispose();
            }
        }
    }
}
